import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Button,
  Form,
  Input,
  Space,
  Table,
  Switch,
  Image,
  Modal,
  message
} from 'antd'
import type { FormInstance } from 'antd'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { NavLink } from 'react-router-dom'
import { getUserList, addUser, editUser, delUser } from '@/api/user'
import { User } from '@/types/user'
import type { ColumnsType } from 'antd/es/table'
const { confirm } = Modal

const items = [
  {
    title: <NavLink to='/'>首页</NavLink>
  },
  {
    title: '用户管理'
  },
  {
    title: '用户列表'
  }
]

export default class MyUser extends Component {
  state = {
    page: 1,
    pageSize: 2,
    nickname: '', // 昵称
    total: 0,
    userList: [] as User[],
    isModalOpen: false, //弹出框是否显示
    mode: 'add', //模态框的值
    isChecked: true
  }

  columns: ColumnsType<User> = [
    {
      title: '用户名',
      dataIndex: 'adminname',
      render: text => <a>{text}</a>
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname'
    },
    {
      title: '用户头像',
      dataIndex: 'avatar',
      render: avatar => {
        return <Image style={{ width: 50, height: 50 }} src={avatar} />
      }
    },
    {
      title: '状态',
      render: (_, { status }) => {
        return <Switch checked={status === 1} />
      }
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space size='middle'>
          <Button type='primary' onClick={() => this.edit(record)}>
            修改
          </Button>
          <Button
            danger
            type='primary'
            onClick={() => {
              this.del(record.adminid)
            }}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  // 为了获取Form表单实例
  formRef = React.createRef<FormInstance>()

  // 获取弹出框的表单实例
  modalFrom = React.createRef<FormInstance>()

  getUserListData = async () => {
    const res = await getUserList({
      page: this.state.page,
      pageSize: this.state.pageSize,
      nickname: this.state.nickname
    })

    this.setState({
      userList: res.data.items,
      total: res.data.total
    })
  }

  search = () => {
    const res = this.formRef.current?.getFieldValue('nickname')
    console.log(res)

    this.state.nickname = res
    this.getUserListData()
  }

  componentDidMount (): void {
    this.getUserListData()
  }

  handleOk = async () => {
    try {
      await this.modalFrom.current?.validateFields()
      console.log(this.modalFrom.current?.getFieldsValue())
      const obj = this.modalFrom.current?.getFieldsValue()
      let res
      if (this.state.mode === 'add') {
        res = await addUser(obj)
      } else {
        obj.adminid = this.adminid
        res = await editUser(obj)
      }

      // 消息提示
      message.success({ content: res.message, duration: 0.8 })

      this.getUserListData()

      // 关闭弹窗
      this.setState({
        isModalOpen: false,
        mode: 'add'
      })
      this.modalFrom.current?.resetFields()
    } catch (error) {
      console.log(error)
    }
  }

  adminid = ''
  edit = (user: User) => {
    this.adminid = user.adminid

    this.setState(
      {
        mode: 'edit',
        isModalOpen: true,
        isChecked: user.status === 1 ? true : false
      },
      () => {
        this.modalFrom.current?.setFieldsValue({
          adminname: user.adminname,
          nickname: user.nickname
        })
      }
    )
  }

  del = (adminid: string) => {
    confirm({
      title: '提示',
      icon: <ExclamationCircleFilled />,
      content: '确定删除该条数据吗',
      onOk: async () => {
        await delUser({ adminid })
        this.setState(
          {
            page: 1
          },
          () => {
            this.getUserListData()
          }
        )
      },
      onCancel () {
        console.log('Cancel')
      }
    })
  }

  cancel = () => {
    this.setState({ isModalOpen: false, mode: 'add' })
    this.modalFrom.current?.resetFields()
  }

  render () {
    return (
      <div>
        <Card>
          <Breadcrumb items={items} />
          <Form
            layout={'inline'}
            ref={this.formRef}
            style={{ marginTop: 20 }}
            size='large'
          >
            <Form.Item label='昵称' name='nickname'>
              <Input placeholder='请输入昵称进行搜索' />
            </Form.Item>
            <Form.Item>
              <Space />
              <Button
                type='primary'
                style={{ marginRight: 20 }}
                onClick={this.search}
              >
                搜索
              </Button>
              <Button
                type='default'
                onClick={() => this.setState({ isModalOpen: true })}
              >
                +新增用户
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Card style={{ marginTop: 10 }}>
          <Table
            rowKey='adminid'
            columns={this.columns}
            dataSource={this.state.userList}
            pagination={{
              position: ['bottomCenter'],
              showSizeChanger: true,
              showQuickJumper: true,
              total: this.state.total,
              showTotal: () => `共${this.state.total}条`,
              current: this.state.page,
              pageSize: this.state.pageSize,
              pageSizeOptions: [2, 5, 10],
              onChange: (page, pageSize) => {
                this.setState(
                  {
                    page,
                    pageSize
                  },
                  () => {
                    this.getUserListData()
                  }
                )
              }
            }}
          />
        </Card>

        <Modal
          title={this.state.mode === 'add' ? '新增用户' : '修改用户'}
          open={this.state.isModalOpen}
          onOk={this.handleOk}
          onCancel={this.cancel}
        >
          <Form
            ref={this.modalFrom}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              label='用户名'
              name='adminname'
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input disabled={this.state.mode === 'edit'} />
            </Form.Item>

            <Form.Item
              label='用户昵称'
              name='nickname'
              rules={[{ required: true, message: '请输入用户昵称!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item label='状态' name='status'>
              <Switch
                checked={this.state.isChecked}
                onChange={(checked: boolean) =>
                  this.setState({
                    isChecked: checked
                  })
                }
              />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
